package petshop.agronunes.dao;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import petshop.agronunes.entidade.Especie;


public class EspecieDAO {
	private Session session;
	
	public EspecieDAO() {
		this.session = HibernateUtil.getSession();
	}
	
	public Integer insert(Especie especie) throws Exception {
		try {
			Integer id = (Integer) session.save(especie);
			session.beginTransaction().commit();
			return id;
		} catch(Exception e) {
			throw new Exception(e);
		} finally {
			session.close();
		}
	}
	
	public void update(Especie especie) throws Exception {
		try {
			session.update(especie);
			session.beginTransaction().commit();
		} catch(Exception e) {
			throw new Exception(e);
		} finally {
			session.close();
		}
	}
	
	@SuppressWarnings("unchecked")
	public List<Especie> getAll() throws Exception {
		try {
			Criteria query = session.createCriteria(Especie.class);
			return query.list();
		} catch(Exception e) {
			throw new Exception(e);
		} finally {
			session.close();
		}
	}
	
	public Especie GetById(Integer id) throws Exception {
		try {
			Criteria query = session.createCriteria(Especie.class);
			query.add(Restrictions.idEq(id));
			return (Especie) query.uniqueResult();
		} catch(Exception e) {
			throw new Exception(e);
		} finally {
			session.close();
		}
	}
	
	public void delete(Especie especie) throws Exception {
		try {
			session.delete(especie);
			session.beginTransaction().commit();
		} catch(Exception e) {
			throw new Exception(e);
		} finally {
			session.close();
		}
	}
}